/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server.managerServer;

import protocol.ThreadWorker;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import server.PollList;

/**
 * Listens on the given tcp port for inbound "admin" connections
 * after a connection is created, a separated Thread (ThreadWorker) 
 * is created, to serve the client
 */
public class Listener extends Thread {

    int listeningPort;
    Thread serverThread;
    ServerSocket listenSock;
    PollList polls;

    public Listener(int _listeningPort, PollList _polls) {
        super();
        this.listeningPort = _listeningPort;
        this.polls = _polls;
    }

    @Override
    public void run() {
        try {
            this.loop();
        } catch (Exception ex) {
            Logger.getLogger(Listener.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /*
     * Listening on the given socket in an infinite loop
     */
    private void loop() throws Exception {
        this.listenSock = new ServerSocket(listeningPort);
        System.out.println("Listening to port " + listeningPort + "\n");

        while (true) {
            Socket clientSock = listenSock.accept();
            ThreadWorker request = new ServerWorker(clientSock,this.polls);
            request.start();
        }
    }
}
